﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using CommonFunction;
using System.Linq;

namespace RouletteD5
{
    public partial class FrmConfiguration : Form
    {
        XmlDocument xmlDoc = new XmlDocument();

        public FrmConfiguration()
        {
            InitializeComponent();
        }

        private void cboFollowingStrategy_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadFollowingStrategy((Common.STRATEGIES)cboFollowingStrategy.SelectedIndex);
        }

        private void cboTypeOfStrategy_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadOtherStrategy((Common.STRATEGIES)cboTypeOfStrategy.SelectedIndex);
        }

        private void chkStrategy_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;

            if (chk.Name == chkOtherStrategy.Name)
            {
                chkFollowing.Checked = !chk.Checked;
                grpFollowing.Enabled = chkFollowing.Checked;
            }
            else
            {
                chkOtherStrategy.Checked = !chk.Checked;
                grpOtherStrategy.Enabled = chkOtherStrategy.Checked;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (Updated()) MessageBox.Show("The data saved successfully", "Saving data configuration", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            var confirm = MessageBox.Show("You want to reset data ?", "Data Configuration confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (confirm == System.Windows.Forms.DialogResult.OK)
            {
                LoadConfigData();
                LoadFollowingStrategy((Common.STRATEGIES)cboFollowingStrategy.SelectedIndex);
                LoadOtherStrategy((Common.STRATEGIES)cboTypeOfStrategy.SelectedIndex);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region "Load data configuration"

        public bool InitForm()
        {            
            LoadGridData();
            LoadConfigData();

            cboTypeOfStrategy.SelectedIndex = 3;
            cboFollowingStrategy.SelectedIndex = 0;

            return true;
        }

        private bool LoadGridData()
        {
            try
            {
                //define datasource of grid
                DataTable betDataList = new DataTable();
                DataColumn newCol = new DataColumn("Number", typeof(string));
                betDataList.Columns.Add(newCol);

                for (int i = 1; i <= 30; i++)
                {
                    newCol = new DataColumn(string.Format("Bet{0}", i), typeof(int));
                    newCol.DefaultValue = 0;
                    betDataList.Columns.Add(newCol);
                }

                //fill in predefine data for datasource
                DataRow newRow = betDataList.NewRow();
                newRow["Number"] = "*";
                betDataList.Rows.Add(newRow);
                newRow = betDataList.NewRow();
                newRow["Number"] = "00";
                betDataList.Rows.Add(newRow);

                for (int i = 0; i <= 36; i++)
                {
                    newRow = betDataList.NewRow();
                    newRow["Number"] = i.ToString();
                    betDataList.Rows.Add(newRow);
                }

                //set datasource to grid
                gridOtherStrategy.DataSource = betDataList.DefaultView;
                gridOtherStrategy.Columns["Number"].Frozen = true;
                gridOtherStrategy.Columns["Number"].ReadOnly = true;
                gridOtherStrategy.Columns["Number"].DefaultCellStyle.Font = new System.Drawing.Font("", 12, System.Drawing.FontStyle.Bold);
                gridOtherStrategy.Columns["Number"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                gridOtherStrategy.Columns["Number"].Width = 70;

                for (int i = 1; i <= 30; i++)
                {
                    gridOtherStrategy.Columns[i].Width = 60;
                    gridOtherStrategy.Columns[i].HeaderText = string.Format("Bet {0}", i);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }

        private void LoadConfigData()
        {   
            try
            {
                var dataFilePath = Path.Combine(Application.StartupPath, ConfigurationManager.AppSettings["DataFilePath"]);
                if (!File.Exists(dataFilePath)) return;
                xmlDoc.Load(dataFilePath);

                txtStopWinning.Text = xmlDoc.DocumentElement.FirstChild.InnerText;
                txtStopLosing.Text = xmlDoc.DocumentElement.ChildNodes[1].InnerText;
                txtKeepAlive.Text = xmlDoc.DocumentElement.ChildNodes[2].InnerText;

                if (xmlDoc.DocumentElement.ChildNodes[3].InnerText == "1")
                    chkFollowing.Checked = false;
                else
                    chkFollowing.Checked = true;

                grpFollowing.Enabled = chkFollowing.Checked;
                chkOtherStrategy.Checked = !chkFollowing.Checked;
                grpOtherStrategy.Enabled = chkOtherStrategy.Checked;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading data configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadFollowingStrategy(Common.STRATEGIES strategy)
        {            
            try
            {                
                string valueList = string.Empty;

                switch (strategy)
                {
                    case Common.STRATEGIES.BLACK_RED:
                        valueList = xmlDoc.DocumentElement.ChildNodes[4].FirstChild.InnerText;                        
                        break;

                    case Common.STRATEGIES.EVEN_ODD:
                        valueList = xmlDoc.DocumentElement.ChildNodes[4].ChildNodes[1].InnerText;
                        break;

                    case Common.STRATEGIES.HIGH_LOW:
                        valueList = xmlDoc.DocumentElement.ChildNodes[4].ChildNodes[2].InnerText;
                        break;

                    default: return;
                }

                string ctrlName = string.Empty;
                var valueArr = valueList.Split(";".ToCharArray());
                for (int i = 0; i < valueArr.Length; i++)
                {
                    ctrlName = string.Format("txtF{0}", (i + 1).ToString("00"));
                    grpFollowing.Controls[ctrlName].Text = valueArr[i];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading data configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadOtherStrategy(Common.STRATEGIES strategy)
        {
            try
            {
                XmlNode strategyData = null;

                switch (strategy)
                {
                    case Common.STRATEGIES.BLACK_RED:
                        strategyData = xmlDoc.DocumentElement.ChildNodes[5].FirstChild;
                        break;

                    case Common.STRATEGIES.EVEN_ODD:
                        strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[1];
                        break;

                    case Common.STRATEGIES.HIGH_LOW:
                        strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[2];
                        break;

                    case Common.STRATEGIES.DOZENS:
                        strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[4];
                        break;

                    case Common.STRATEGIES.COLUMNS:
                        strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[3];
                        break;

                    case Common.STRATEGIES.NUMBERS:
                        strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[5];
                        break;

                    default: return;
                }

                cboWaiting.Text = strategyData.FirstChild.InnerText;

                int iRow = 0;
                foreach (XmlNode iNode in strategyData.ChildNodes)
                {
                    if (iNode.Name == "Wait") continue;
                    var valueList = iNode.InnerText.Split(";".ToCharArray());
                    for (int i = 0; i < valueList.Length; i++)
                    {                        
                        gridOtherStrategy.Rows[iRow].Cells[i + 1].Value = valueList[i];
                        if (valueList[i] != "0")
                            gridOtherStrategy.Rows[iRow].Cells[i + 1].Style.ForeColor = System.Drawing.Color.Red;
                        else
                            gridOtherStrategy.Rows[iRow].Cells[i + 1].Style.ForeColor = System.Drawing.Color.Black;
                    }
                    iRow++;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading data configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region "Update data configuration"

        private bool Updated()
        {
            bool success = false;
            var dataFilePath = Path.Combine(Application.StartupPath, ConfigurationManager.AppSettings["DataFilePath"]);

            try
            {
                if (string.IsNullOrEmpty(txtStopWinning.Text.Trim())) txtStopWinning.Text = "0";
                xmlDoc.DocumentElement.FirstChild.InnerText = txtStopWinning.Text;
                if (string.IsNullOrEmpty(txtStopLosing.Text.Trim())) txtStopLosing.Text = "0";
                xmlDoc.DocumentElement.ChildNodes[1].InnerText = txtStopLosing.Text;
                if (string.IsNullOrEmpty(txtKeepAlive.Text.Trim())) txtKeepAlive.Text = "0";
                xmlDoc.DocumentElement.ChildNodes[2].InnerText = txtKeepAlive.Text;

                //other strategy
                if (chkOtherStrategy.Checked)
                {
                    xmlDoc.DocumentElement.ChildNodes[3].InnerText = "1";

                    var otherStrategy = (Common.STRATEGIES)cboTypeOfStrategy.SelectedIndex;
                    XmlNode strategyData = null;
                    switch (otherStrategy)
                    {
                        case Common.STRATEGIES.BLACK_RED:
                            strategyData = xmlDoc.DocumentElement.ChildNodes[5].FirstChild;
                            break;

                        case Common.STRATEGIES.EVEN_ODD:
                            strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[1];
                            break;

                        case Common.STRATEGIES.HIGH_LOW:
                            strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[2];
                            break;

                        case Common.STRATEGIES.DOZENS:
                            strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[4];
                            break;

                        case Common.STRATEGIES.COLUMNS:
                            strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[3];
                            break;

                        case Common.STRATEGIES.NUMBERS:
                            strategyData = xmlDoc.DocumentElement.ChildNodes[5].ChildNodes[5];
                            break;

                        default: break;
                    }

                    strategyData.FirstChild.InnerText = cboWaiting.Text;
                    string strValue = string.Empty;
                    for (int i = 0; i < gridOtherStrategy.RowCount; i++)
                    {
                        strValue = "";
                        for (int j = 1; j < gridOtherStrategy.ColumnCount; j++)
                        {
                            strValue += gridOtherStrategy[j, i].Value.ToString() + ";";
                        }
                        strValue = strValue.Substring(0, strValue.Length - 1);
                        strategyData.ChildNodes[i + 1].InnerText = strValue;
                    }                    
                }
                //following strategy
                else
                {
                    xmlDoc.DocumentElement.ChildNodes[3].InnerText = "0";
                    var followStrategy = (Common.STRATEGIES)cboFollowingStrategy.SelectedIndex;
                    string valueList = string.Join(";", grpFollowing.Controls.Cast<Control>()
                        .Where(t => t.Name.StartsWith("txtF")).OrderBy(t => t.Name)
                        .Select(t => t.Text).ToArray());
                    
                    switch (followStrategy)
                    {
                        case Common.STRATEGIES.BLACK_RED:
                            xmlDoc.DocumentElement.ChildNodes[4].FirstChild.InnerText = valueList;
                            break;

                        case Common.STRATEGIES.EVEN_ODD:
                            xmlDoc.DocumentElement.ChildNodes[4].ChildNodes[1].InnerText = valueList;
                            break;

                        case Common.STRATEGIES.HIGH_LOW:
                            xmlDoc.DocumentElement.ChildNodes[4].LastChild.InnerText = valueList;
                            break;

                        default: break;
                    }
                }

                xmlDoc.Save(dataFilePath);
                success = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading data configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                xmlDoc.Load(dataFilePath);
            }

            return success;
        }

        #endregion
    }
}
